package com.camelot.boot.module.ai.service.chat;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.camelot.boot.framework.ai.core.enums.AiPlatformEnum;
import com.camelot.boot.framework.ai.core.factory.AiModelFactory;
import com.camelot.boot.framework.ai.core.util.AiUtils;
import com.camelot.boot.framework.common.pojo.CommonResult;
import com.camelot.boot.framework.common.pojo.PageResult;
import com.camelot.boot.framework.common.util.object.BeanUtils;
import com.camelot.boot.framework.tenant.core.util.TenantUtils;
import com.camelot.boot.module.ai.controller.admin.chat.dto.AiResumeTransferDTO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.message.AiChatMessagePageReqVO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.message.AiChatMessageRespVO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.message.AiChatMessageSendReqVO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.message.AiChatMessageSendRespVO;
import com.camelot.boot.module.ai.dal.dataobject.chat.AiChatConversationDO;
import com.camelot.boot.module.ai.dal.dataobject.chat.AiChatMessageDO;
import com.camelot.boot.module.ai.dal.dataobject.chat.AiResumeTransferDO;
import com.camelot.boot.module.ai.dal.dataobject.knowledge.AiKnowledgeDocumentDO;
import com.camelot.boot.module.ai.dal.dataobject.model.AiChatRoleDO;
import com.camelot.boot.module.ai.dal.dataobject.model.AiModelDO;
import com.camelot.boot.module.ai.dal.dataobject.model.AiToolDO;
import com.camelot.boot.module.ai.dal.mysql.chat.AiChatMessageMapper;
import com.camelot.boot.module.ai.enums.ErrorCodeConstants;
import com.camelot.boot.module.ai.service.knowledge.AiKnowledgeDocumentService;
import com.camelot.boot.module.ai.service.knowledge.AiKnowledgeSegmentService;
import com.camelot.boot.module.ai.service.knowledge.bo.AiKnowledgeSegmentSearchReqBO;
import com.camelot.boot.module.ai.service.knowledge.bo.AiKnowledgeSegmentSearchRespBO;
import com.camelot.boot.module.ai.service.model.AiChatRoleService;
import com.camelot.boot.module.ai.service.model.AiModelService;
import com.camelot.boot.module.ai.service.model.AiToolService;
import com.camelot.boot.module.ai.util.DOCXUtil;
import com.camelot.boot.module.system.api.aicompany.CompanyRequirementApi;
import com.camelot.boot.module.system.api.aicompany.CompanyRequirementRespDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.StreamingChatModel;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.camelot.boot.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.camelot.boot.framework.common.pojo.CommonResult.error;
import static com.camelot.boot.framework.common.pojo.CommonResult.success;
import static com.camelot.boot.framework.common.util.collection.CollectionUtils.convertList;
import static com.camelot.boot.framework.common.util.collection.CollectionUtils.convertSet;
import static com.camelot.boot.module.ai.enums.ErrorCodeConstants.CHAT_CONVERSATION_NOT_EXISTS;
import static com.camelot.boot.module.ai.enums.ErrorCodeConstants.CHAT_MESSAGE_NOT_EXIST;

/**
 * AI 聊天消息 Service 实现类
 *
 * @author fansili
 */
@Service
@Slf4j
public class AiChatMessageServiceImpl implements AiChatMessageService {

    /**
     * 知识库转 {@link UserMessage} 的内容模版
     */
    private static final String KNOWLEDGE_USER_MESSAGE_TEMPLATE = "使用 <Reference></Reference> 标记中的内容作为本次对话的参考:\n\n" +
            "%s\n\n" + // 多个 <Reference></Reference> 的拼接
            "回答要求：\n- 避免提及你是从 <Reference></Reference> 获取的知识。";

    @Resource
    private AiChatMessageMapper chatMessageMapper;

    @Resource
    private AiChatConversationService chatConversationService;
    @Resource
    private AiChatRoleService chatRoleService;
    @Resource
    private AiModelService modalService;
    @Resource
    private AiKnowledgeSegmentService knowledgeSegmentService;
    @Resource
    private AiKnowledgeDocumentService knowledgeDocumentService;
    @Resource
    private AiToolService toolService;
    @Resource
    private CompanyRequirementApi companyRequirementApi;
    @Resource
    private AiModelFactory aiModelFactory;
    @Resource
    private AiResumeTransferService aiResumeTransferService;

    @Transactional(rollbackFor = Exception.class)
    public AiChatMessageSendRespVO sendMessage(AiChatMessageSendReqVO sendReqVO, Long userId) {
        // 1.1 校验对话存在
        AiChatConversationDO conversation = chatConversationService
                .validateChatConversationExists(sendReqVO.getConversationId());
        if (ObjUtil.notEqual(conversation.getUserId(), userId)) {
            throw exception(CHAT_CONVERSATION_NOT_EXISTS);
        }
        List<AiChatMessageDO> historyMessages = chatMessageMapper.selectListByConversationId(conversation.getId());
        // 1.2 校验模型
        AiModelDO model = modalService.validateModel(conversation.getModelId());
        ChatModel chatModel = modalService.getChatModel(model.getId());

        // 2. 知识库找回
        List<AiKnowledgeSegmentSearchRespBO> knowledgeSegments = recallKnowledgeSegment(sendReqVO.getContent(),
                conversation);

        CompanyRequirementRespDTO requirementRespDTO = companyRequirementApi.getById(conversation.getCompanyRequirementId());
        String send = requirementRespDTO != null ? requirementRespDTO.getFocus() : sendReqVO.getContent();
        // 3. 插入 user 发送消息
        AiChatMessageDO userMessage = createChatMessage(conversation.getId(), null, model,
                userId, conversation.getRoleId(),conversation.getCompanyRequirementId(),conversation.getCompanyId(),send, MessageType.USER, sendReqVO.getContent(), sendReqVO.getUseContext(),
                null);

        // 3.1 插入 assistant 接收消息
        AiChatMessageDO assistantMessage = createChatMessage(conversation.getId(), userMessage.getId(), model,
                userId, conversation.getRoleId(),conversation.getCompanyRequirementId(),conversation.getCompanyId(),send, MessageType.ASSISTANT, "", sendReqVO.getUseContext(),
                knowledgeSegments);

        // 3.2 创建 chat 需要的 Prompt
        Prompt prompt = buildPrompt(conversation, requirementRespDTO,historyMessages, knowledgeSegments, model, sendReqVO);
        ChatResponse chatResponse = chatModel.call(prompt);

        // 3.3 更新响应内容
        String newContent = chatResponse.getResult().getOutput().getText();
        if (requirementRespDTO != null){
            newContent = newContent.replaceAll("```","");
            newContent = newContent.replaceFirst("json","");
            ObjectMapper mapper = new ObjectMapper();
            String score;
            String content;
            String candidateName;
            String mobile;
            try {
                JsonNode jsonNode = mapper.readTree(newContent);
                score = jsonNode.get("score").asText();
                content = jsonNode.get("content").asText();
                candidateName = jsonNode.get("candidateName").asText();
                mobile = jsonNode.get("mobile").asText();
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            chatMessageMapper.updateById(new AiChatMessageDO().setId(assistantMessage.getId()).setScore(new BigDecimal(score)).setContent(content).setCandidateName(candidateName).setMobile(mobile));
        }
        // 3.4 响应结果
        List<AiChatMessageRespVO.KnowledgeSegment> segments = BeanUtils.toBean(knowledgeSegments,
                AiChatMessageRespVO.KnowledgeSegment.class,
                segment -> {
                    AiKnowledgeDocumentDO document = knowledgeDocumentService
                            .getKnowledgeDocument(segment.getDocumentId());
                    segment.setDocumentName(document != null ? document.getName() : null);
                });
        return new AiChatMessageSendRespVO()
                .setSend(BeanUtils.toBean(userMessage, AiChatMessageSendRespVO.Message.class))
                .setReceive(BeanUtils.toBean(assistantMessage, AiChatMessageSendRespVO.Message.class)
                        .setContent(newContent).setSegments(segments));
    }

    @Override
    public Flux<CommonResult<AiChatMessageSendRespVO>> sendChatMessageStream(AiChatMessageSendReqVO sendReqVO,
            Long userId) {
        // 1.1 校验对话存在
        AiChatConversationDO conversation = chatConversationService
                .validateChatConversationExists(sendReqVO.getConversationId());
        if (ObjUtil.notEqual(conversation.getUserId(), userId)) {
            throw exception(CHAT_CONVERSATION_NOT_EXISTS);
        }
        List<AiChatMessageDO> historyMessages = chatMessageMapper.selectListByConversationId(conversation.getId());
        // 1.2 校验模型
        AiModelDO model = modalService.validateModel(conversation.getModelId());
        StreamingChatModel chatModel = modalService.getChatModel(model.getId());

        // 2. 知识库找回
        List<AiKnowledgeSegmentSearchRespBO> knowledgeSegments = recallKnowledgeSegment(sendReqVO.getContent(),
                conversation);

        CompanyRequirementRespDTO requirementRespDTO = companyRequirementApi.getById(conversation.getCompanyRequirementId());
        String send = requirementRespDTO != null ? requirementRespDTO.getFocus() : sendReqVO.getContent();
        // 3. 插入 user 发送消息
        AiChatMessageDO userMessage = createChatMessage(conversation.getId(), null, model,
                userId, conversation.getRoleId(),conversation.getCompanyRequirementId(),conversation.getCompanyId(),send, MessageType.USER, sendReqVO.getContent(), sendReqVO.getUseContext(),
                null);

        // 4.1 插入 assistant 接收消息
        AiChatMessageDO assistantMessage = createChatMessage(conversation.getId(), userMessage.getId(), model,
                userId, conversation.getRoleId(),conversation.getCompanyRequirementId(),conversation.getCompanyId(),send, MessageType.ASSISTANT, "", sendReqVO.getUseContext(),
                knowledgeSegments);

        // 4.2 构建 Prompt，并进行调用
        Prompt prompt = buildPrompt(conversation, requirementRespDTO,historyMessages, knowledgeSegments, model, sendReqVO);
        Flux<ChatResponse> streamResponse = chatModel.stream(prompt);

        // 4.3 流式返回
        StringBuffer contentBuffer = new StringBuffer();
        return streamResponse.map(chunk -> {
            // 处理知识库的返回，只有首次才有
            List<AiChatMessageRespVO.KnowledgeSegment> segments = null;
            if (StrUtil.isEmpty(contentBuffer)) {
                segments = BeanUtils.toBean(knowledgeSegments, AiChatMessageRespVO.KnowledgeSegment.class,
                        segment -> TenantUtils.executeIgnore(() -> {
                            AiKnowledgeDocumentDO document = knowledgeDocumentService
                                    .getKnowledgeDocument(segment.getDocumentId());
                            segment.setDocumentName(document != null ? document.getName() : null);
                        }));
            }
            // 响应结果
            String newContent = chunk.getResult() != null ? chunk.getResult().getOutput().getText() : null;
            newContent = StrUtil.nullToDefault(newContent, ""); // 避免 null 的 情况
            contentBuffer.append(newContent);
            return success(new AiChatMessageSendRespVO()
                    .setSend(BeanUtils.toBean(userMessage, AiChatMessageSendRespVO.Message.class))
                    .setReceive(BeanUtils.toBean(assistantMessage, AiChatMessageSendRespVO.Message.class)
                            .setContent(newContent).setSegments(segments)));
        }).doOnComplete(() -> {
            String newContent = contentBuffer.toString();
            if (requirementRespDTO != null){
                newContent = newContent.replaceAll("```","");
                newContent = newContent.replaceFirst("json","");
                ObjectMapper mapper = new ObjectMapper();
                String score;
                String content;
                String candidateName;
                String mobile;
                try {
                    JsonNode jsonNode = mapper.readTree(newContent);
                    score = jsonNode.get("score").asText();
                    content = jsonNode.get("content").asText();
                    candidateName = jsonNode.get("candidateName").asText();
                    mobile = jsonNode.get("mobile").asText();
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                // 忽略租户，因为 Flux 异步无法透传租户
                TenantUtils.executeIgnore(() -> chatMessageMapper.updateById(
                        new AiChatMessageDO().setId(assistantMessage.getId()).setContent(content).setCandidateName(candidateName).setMobile(mobile).setScore(new BigDecimal(score))));
            }

        }).doOnError(throwable -> {
            log.error("[sendChatMessageStream][userId({}) sendReqVO({}) 发生异常]", userId, sendReqVO, throwable);
            // 忽略租户，因为 Flux 异步无法透传租户
            TenantUtils.executeIgnore(() -> chatMessageMapper.updateById(
                    new AiChatMessageDO().setId(assistantMessage.getId()).setContent(throwable.getMessage())));
        }).onErrorResume(error -> Flux.just(error(ErrorCodeConstants.CHAT_STREAM_ERROR)));
    }

    private List<AiKnowledgeSegmentSearchRespBO> recallKnowledgeSegment(String content,
            AiChatConversationDO conversation) {
        // 1. 查询聊天角色
        if (conversation == null || conversation.getRoleId() == null) {
            return Collections.emptyList();
        }
        AiChatRoleDO role = chatRoleService.getChatRole(conversation.getRoleId());
        if (role == null || CollUtil.isEmpty(role.getKnowledgeIds())) {
            return Collections.emptyList();
        }

        // 2. 遍历找回
        List<AiKnowledgeSegmentSearchRespBO> knowledgeSegments = new ArrayList<>();
        for (Long knowledgeId : role.getKnowledgeIds()) {
            knowledgeSegments.addAll(knowledgeSegmentService.searchKnowledgeSegment(new AiKnowledgeSegmentSearchReqBO()
                    .setKnowledgeId(knowledgeId).setContent(content)));
        }
        return knowledgeSegments;
    }

    private Prompt buildPrompt(AiChatConversationDO conversation, CompanyRequirementRespDTO requirement, List<AiChatMessageDO> messages,
            List<AiKnowledgeSegmentSearchRespBO> knowledgeSegments,
            AiModelDO model, AiChatMessageSendReqVO sendReqVO) {
        List<Message> chatMessages = new ArrayList<>();
        // 1.1 System Context 角色设定
        if (requirement != null) {

            chatMessages.add(new SystemMessage(requirement.getFocus()+",对简历进行打分，满分10分，分析结果、得分候选人姓名、电话分别按严格的json格式返回，分析结果最多100字并作为一整串key为content，得分为score，候选人姓名为candidateName，电话为mobile"));
        }

        // 1.2 历史 history message 历史消息
        List<AiChatMessageDO> contextMessages = filterContextMessages(messages, conversation, sendReqVO);
        contextMessages
                .forEach(message -> chatMessages.add(AiUtils.buildMessage(message.getType(), message.getContent())));

        // 1.3 当前 user message 新发送消息
        chatMessages.add(new UserMessage(sendReqVO.getContent()));

        // 1.4 知识库，通过 UserMessage 实现
        if (CollUtil.isNotEmpty(knowledgeSegments)) {
            String reference = knowledgeSegments.stream()
                    .map(segment -> "<Reference>" + segment.getContent() + "</Reference>")
                    .collect(Collectors.joining("\n\n"));
            chatMessages.add(new UserMessage(String.format(KNOWLEDGE_USER_MESSAGE_TEMPLATE, reference)));
        }

        // 2.1 查询 tool 工具
        Set<String> toolNames = null;
        if (conversation.getRoleId() != null) {
            AiChatRoleDO chatRole = chatRoleService.getChatRole(conversation.getRoleId());
            if (chatRole != null && CollUtil.isNotEmpty(chatRole.getToolIds())) {
                toolNames = convertSet(toolService.getToolList(chatRole.getToolIds()), AiToolDO::getName);
            }
        }
        // 2.2 构建 ChatOptions 对象
        AiPlatformEnum platform = AiPlatformEnum.validatePlatform(model.getPlatform());
        ChatOptions chatOptions = AiUtils.buildChatOptions(platform, model.getModel(),
                conversation.getTemperature(), conversation.getMaxTokens(), toolNames);
        return new Prompt(chatMessages, chatOptions);
    }

    /**
     * 从历史消息中，获得倒序的 n 组消息作为消息上下文
     * <p>
     * n 组：指的是 user + assistant 形成一组
     *
     * @param messages     消息列表
     * @param conversation 对话
     * @param sendReqVO    发送请求
     * @return 消息上下文
     */
    private List<AiChatMessageDO> filterContextMessages(List<AiChatMessageDO> messages,
            AiChatConversationDO conversation,
            AiChatMessageSendReqVO sendReqVO) {
        if (conversation.getMaxContexts() == null || ObjUtil.notEqual(sendReqVO.getUseContext(), Boolean.TRUE)) {
            return Collections.emptyList();
        }
        List<AiChatMessageDO> contextMessages = new ArrayList<>(conversation.getMaxContexts() * 2);
        for (int i = messages.size() - 1; i >= 0; i--) {
            AiChatMessageDO assistantMessage = CollUtil.get(messages, i);
            if (assistantMessage == null || assistantMessage.getReplyId() == null) {
                continue;
            }
            AiChatMessageDO userMessage = CollUtil.get(messages, i - 1);
            if (userMessage == null
                    || ObjUtil.notEqual(assistantMessage.getReplyId(), userMessage.getId())
                    || StrUtil.isEmpty(assistantMessage.getContent())) {
                continue;
            }
            // 由于后续要 reverse 反转，所以先添加 assistantMessage
            contextMessages.add(assistantMessage);
            contextMessages.add(userMessage);
            // 超过最大上下文，结束
            if (contextMessages.size() >= conversation.getMaxContexts() * 2) {
                break;
            }
        }
        Collections.reverse(contextMessages);
        return contextMessages;
    }

    private AiChatMessageDO createChatMessage(Long conversationId, Long replyId,
                                              AiModelDO model, Long userId, Long roleId,
                                              Long companyRequirementId, Long companyId, String systemPrompt,
                                              MessageType messageType, String content, Boolean useContext,
                                              List<AiKnowledgeSegmentSearchRespBO> knowledgeSegments) {
        AiChatMessageDO message = new AiChatMessageDO().setConversationId(conversationId).setReplyId(replyId)
                .setModel(model.getModel()).setModelId(model.getId()).setUserId(userId).setRoleId(roleId)
                .setEmployed(0).setCompanyId(companyId).setCompanyRequirementId(companyRequirementId)
                .setSystemPrompt(systemPrompt)
                .setType(messageType.getValue()).setContent(content).setUseContext(useContext)
                .setSegmentIds(convertList(knowledgeSegments, AiKnowledgeSegmentSearchRespBO::getId));
        message.setCreateTime(LocalDateTime.now());
        if (companyId != null && companyRequirementId != null){
            chatMessageMapper.insert(message);
        }
        return message;
    }

    @Override
    public List<AiChatMessageDO> getChatMessageListByConversationId(Long conversationId) {
        return chatMessageMapper.selectListByConversationId(conversationId);
    }

    @Override
    public void deleteChatMessage(Long id, Long userId) {
        // 1. 校验消息存在
        AiChatMessageDO message = chatMessageMapper.selectById(id);
        if (message == null || ObjUtil.notEqual(message.getUserId(), userId)) {
            throw exception(CHAT_MESSAGE_NOT_EXIST);
        }
        // 2. 执行删除
        chatMessageMapper.deleteById(id);
    }

    @Override
    public void deleteChatMessageByConversationId(Long conversationId, Long userId) {
        // 1. 校验消息存在
        List<AiChatMessageDO> messages = chatMessageMapper.selectListByConversationId(conversationId);
        if (CollUtil.isEmpty(messages) || ObjUtil.notEqual(messages.get(0).getUserId(), userId)) {
            throw exception(CHAT_MESSAGE_NOT_EXIST);
        }
        // 2. 执行删除
        chatMessageMapper.deleteBatchIds(convertList(messages, AiChatMessageDO::getId));
    }

    @Override
    public void deleteChatMessageByAdmin(Long id) {
        // 1. 校验消息存在
        AiChatMessageDO message = chatMessageMapper.selectById(id);
        if (message == null) {
            throw exception(CHAT_MESSAGE_NOT_EXIST);
        }
        // 2. 执行删除
        chatMessageMapper.deleteById(id);
    }

    @Override
    public Map<Long, Integer> getChatMessageCountMap(Collection<Long> conversationIds) {
        return chatMessageMapper.selectCountMapByConversationId(conversationIds);
    }

    @Override
    public PageResult<AiChatMessageDO> getChatMessagePage(AiChatMessagePageReqVO pageReqVO) {
        return chatMessageMapper.selectPage(pageReqVO);
    }

    @Override
    @Async
    public void transfer(AiResumeTransferDTO dto) {
        AiModelDO model = modalService.getByModel("deepseek-reasoner");
        ChatModel chatModel = modalService.getChatModel(model.getId());
        List<Message> messages = new ArrayList<>();
        SystemMessage systemMessage = new SystemMessage("提取简历中的各项信息，提取结果以json返回，姓名key为candidateName，性别key为gender，出生年月key为birthDate，名族key为ethnic，籍贯key为nativePlace，政治面貌key为politicalStatus，婚姻状况key为marriageStatus，职称key为position，工作年限key为workExperience，常驻地址key为address，联系电话key为mobile，身份证号key为idNumber，业务方向key为business，教育培训经历是key为educationBackground的数组，数组里的元素开始时间key为startDate，结束时间为endDate，机构名称key为school，专业key为major，学历key为degree，学历类型key为degreeType，工作经历是key为companies的数组，数组里的元素开始时间key为startDate，结束时间key为endDate，公司全称key为companyName，部门key为department，岗位key为position，项目经验是key为projectExperience的数组，数组里的元素项目名称key为projectName，开始时间key为startDate，结束时间key为endDate，项目描述key为projectDesc限制100个字，工作职责为duty");
        messages.add(systemMessage);
        UserMessage userMessage = new UserMessage(dto.getText());
        messages.add(userMessage);
        // 2.2 构建 ChatOptions 对象
        AiPlatformEnum platform = AiPlatformEnum.validatePlatform(model.getPlatform());
        ChatOptions chatOptions = AiUtils.buildChatOptions(platform, model.getModel(),
                1.0, 4096, null);
        Prompt prompt = new Prompt(messages,chatOptions);
        ChatResponse chatResponse = chatModel.call(prompt);
        String responseText = chatResponse.getResult().getOutput().getText();
        int lastIndex = responseText.lastIndexOf("```");
        responseText = responseText.substring(7,lastIndex);
        log.info("==============AI大模型解析继远简历结果=============");
        log.info(responseText);
        dto.setText(responseText);
        AiResumeTransferDO resumeTransferDO = DOCXUtil.generate(dto);
        if (resumeTransferDO != null){
            aiResumeTransferService.save(resumeTransferDO);
        }
    }

    @Override
    @Async
    public void transferASZ(AiResumeTransferDTO dto) {
        AiModelDO model = modalService.getByModel("deepseek-reasoner");
        ChatModel chatModel = modalService.getChatModel(model.getId());
        List<Message> messages = new ArrayList<>();
        SystemMessage systemMessage = new SystemMessage("提取简历中的各项信息，提取结果以json返回，姓名key为candidateName，性别key为gender，出生年月key为birthDate，名族key为ethnic，籍贯key为nativePlace，政治面貌key为politicalStatus，联系方式key为mobile，职称key为position，身份证号key为idNumber，意向岗位key为expectedPosition，个人主要技能key为workingSkills字符串返回，教育培训经历是key为educationBackground的数组，数组里的元素开始时间key为startDate，结束时间为endDate，机构名称key为school，专业key为major，学历key为degree，学历类型key为degreeType，工作经历是key为companies的数组，数组里的元素开始时间key为startDate，结束时间key为endDate，公司全称key为companyName，部门key为department，岗位key为position，工作描述key为workDesc，项目经验是key为projectExperience的数组，数组里的元素项目名称key为projectName，开始时间key为startDate，结束时间key为endDate，项目描述key为projectDesc，工作职责为duty");
        messages.add(systemMessage);
        UserMessage userMessage = new UserMessage(dto.getText());
        messages.add(userMessage);
        // 2.2 构建 ChatOptions 对象
        AiPlatformEnum platform = AiPlatformEnum.validatePlatform(model.getPlatform());
        ChatOptions chatOptions = AiUtils.buildChatOptions(platform, model.getModel(),
                1.0, 4096, null);
        Prompt prompt = new Prompt(messages,chatOptions);
        ChatResponse chatResponse = chatModel.call(prompt);
        String responseText = chatResponse.getResult().getOutput().getText();
        int lastIndex = responseText.lastIndexOf("```");
        responseText = responseText.substring(7,lastIndex);
        dto.setText(responseText);
        AiResumeTransferDO resumeTransferDO = DOCXUtil.generateASZ(dto);
        if (resumeTransferDO != null){
            aiResumeTransferService.save(resumeTransferDO);
        }
    }

}
